import json
import re
import time

import pymysql
import requests
import smtplib
import execjs
from email.mime.text import MIMEText

tablename = 'nishuihan'
username = 'nishuihanuser'


class AccountChecker:
    def __init__(self):
        self.db = self.connect_database()
        self.cursor = self.db.cursor()
        self.account_info = {
            'price': 0,
            'danjia': 0,
            'qufu': 'None',
            'des': 'None'
        }

    def judgecondition(self, user):
        if user[4] is not None and self.account_info['danjia'] > user[4]:
            return 0
        if user[2] is not None and self.account_info['qufu'] not in user[2]:
            return 0
        if user[3] is not None and self.account_info['price'] > user[3]:
            return 0
        return 1

    @staticmethod
    def js_from_file(file_name):
        """
        读取js文件
        :return:
        """
        with open(file_name, 'r', encoding='UTF-8') as file:
            result = file.read()
        return result

    @staticmethod
    def checkExist(str):
        toFind = ['琼华白羽', '银河星沙', '曦光璞玉', '银河星纱']
        for tmp in toFind:
            if tmp in str:
                return 1
        return 0

    @staticmethod
    def connect_database():
        try:
            return pymysql.connect(host='localhost', user='root', port=3306, db='panzhi')
        except Exception as e:
            print(f'Database connection failed: {e}')
            exit()

    @staticmethod
    def send_email(content, email, myprice):
        mail_host = 'smtp.163.com'
        mail_user = 'vjmbsd'
        mail_pass = 'HVYZEVNOSEOYSADS'
        sender = 'vjmbsd@163.com'
        receivers = [email] if email else ['2391860056@qq.com']

        message = MIMEText(content, 'plain', 'utf-8')
        message['Subject'] = f'逆水寒，{myprice}'
        message['From'] = sender
        message['To'] = ';'.join(receivers)

        try:
            smtp = smtplib.SMTP_SSL("smtp.163.com", 465)
            # 登录到服务
            smtp.login(mail_user, mail_pass)
            # 发送
            smtp.sendmail(sender, receivers, message.as_string())
            # 退出
            smtp.quit()
            print('Email sent successfully')
        except smtplib.SMTPException as e:
            try:
                print(f'Error sending email: {e}')
                mail_user = 'nshyx2292601665'
                mail_pass = 'HNtAz6quUg4ncav3'
                sender = 'nshyx2292601665@163.com'
                smtp = smtplib.SMTP_SSL("smtp.163.com", 465)
                # 登录到服务
                smtp.login(mail_user, mail_pass)
                # 发送
                smtp.sendmail(sender, receivers, message.as_string())
                # 退出
                smtp.quit()
                print('Email1 sent successfully')
            except Exception as e:
                print(f'Error sending email: {e}')



    def check_and_notify_users(self):
        try:
            with self.db.cursor() as cursor:
                sql = f"SELECT * FROM {username} WHERE expiration_date >= CURDATE()"

                cursor.execute(sql)
                users = cursor.fetchall()
                for user in users:
                    if self.judgecondition(user) == 1:
                        self.send_email(
                            self.account_info['des'],
                            user[1],
                            f"总价: {self.account_info['price']} 均价：{self.account_info['danjia']} {self.account_info['qufu']}"
                        )
        except Exception as e:
            print(f"Error checking and notifying users: {e}")

    def getpanzhidata(self):
        url = "https://api.pzds.com/api/web-client/v2/public/goodsPublic/page"
        payload = '''{\"order\":\"DESC\",\"sort\":\"onStandTime\",\"page\":1,\"pageSize\":21,\"action\":{\"gameId\":\"286\",\"goodsCatalogueId\":6,\"merchantMark\":null,\"keywords\":[],\"searchWords\":[],\"searchPropertyIds\":[],\"unionGameIds\":[],\"goodsSearchActions\":[]}}'''
        payload1='''{\"order\":\"DESC\",\"sort\":\"onStandTime\",\"page\":1,\"pageSize\":21,\"action\":{\"gameId\":\"286\",\"goodsCatalogueId\":6,\"merchantMark\":null,\"keywords\":[],\"searchWords\":[],\"searchPropertyIds\":[],\"unionGameIds\":[],\"goodsSearchActions\":[{\"mappingField\":21163,\"searchList\":[\"曦光璞玉\",\"琼华白羽\",\"银河星纱\",\"琼华清露\"],\"searchType\":\"ONE\"}]}}'''
        context1 = execjs.compile(self.js_from_file('./test.js'))
        result1 = context1.call("myJiaMi", str(payload))
        result2 = context1.call("myJiaMi", str(payload1))
        # headers = {
        #     'Accept': 'application/json, text/plain, */*',
        #     'Accept-Encoding': 'gzip, deflate,br,zstd',
        #     'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        #     'Channelinfo': '{"channelCode":null,"tag":null,"channelType":null,"searchWord":"null"}',
        #     'Connection': 'keep-alive',
        #     'Content-Length': '223',
        #     'Content-Type': 'application/json;charset=UTF-8',
        #     'DNT': '1',
        #     'Host': 'api.pzds.com',
        #     'Pzos': 'windows',
        #     'Pzplatform': 'pc',
        #     'Pztimestamp': str(result1['Timestamp']),
        #     'Pzversion': '1.0.0',
        #     'PzversionCode': '1',
        #     'Random': str(result1['Random']),
        #     'Sign': str(result1['strMd5']),
        #     'Skey':'CLIENT',
        #     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0',
        # }
        headers = {
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "channelinfo": "{\"channelCode\":null,\"tag\":null,\"channelType\":null,\"searchWord\":\"null\"}",
            "content-type": "application/json",
            "pzos": "windows",
            "pzplatform": "pc",
            "pztimestamp": str(result1['Timestamp']),
            "pzversion": "1.0.0",
            "pzversioncode": "1",
            "random": str(result1['Random']),
            "sign": str(result1['strMd5']),
            "skey": "CLIENT",

        }
        headers2={
            "accept": "application/json, text/plain, */*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "Channelinfo": "{\"channelCode\":null,\"tag\":null,\"channelType\":null,\"searchWord\":\"null\"}",
            "content-type": "application/json",
            "Pzos": "windows",
            "Pzplatform": "pc",
            "Pztimestamp": str(result2['Timestamp']),
            "Pzversion": "1.0.0",
            "Pzversioncode": "1",
            "Random": str(result2['Random']),
            "Sign": str(result2['strMd5']),
            "Skey": "CLIENT",

        }
        try:
            response = requests.request('post', url, headers=headers, data=payload)
            time.sleep(5)
            response2=requests.request('post', url, headers=headers2, data=payload1.encode('utf-8'))
            mydict = json.loads(response.text)
            mydict1 = json.loads(response2.text)
            a = mydict['data']['records']
            b=mydict1['data']['records']
            for tmp in b:
                try:
                    bianhao = tmp['goodsNo']
                    mysearch = f"select * from {'nishuihan1'} where bianhao='{bianhao}'"
                    self.cursor.execute(mysearch)
                    if not len(self.cursor.fetchall()):
                        self.account_info['price'] = tmp['price']
                        self.account_info['des'] = tmp['title']
                        qufuzuhe = str(tmp['simpleMessage']).split('-')
                        self.account_info['qufu'] = qufuzuhe[len(qufuzuhe) - 1]
                        account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1779601135@qq.com',
                                                       self.account_info['price'] )
                        if '曦光璞玉'   not in  self.account_info['des']:
                        	account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1534326708@qq.com',
                                                       self.account_info['price'] )
                        account_checker.send_email(
                            self.account_info['qufu'] + self.account_info['des'],
                            'w17606748805@163.com',
                            self.account_info['price'])
                        # account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1491012675@qq.com',
                        #                            self.account_info['price'] )
                        sql = f"insert into {'nishuihan1'}(bianhao,price,des,qufu) values('{bianhao}',{self.account_info['price']},'{self.account_info['des'][:500]}','{self.account_info['qufu']}') "
                        self.cursor.execute(sql)
                        self.db.commit()
                except Exception as eee:
                    print('getpanzhidata_b:' + eee.__str__())
            for tmp in a:
                try:
                    bianhao = tmp['goodsNo']
                    mysearch = f"select * from {tablename} where bianhao='{bianhao}'"
                    self.cursor.execute(mysearch)
                    if not len(self.cursor.fetchall()):
                        self.account_info['price'] = tmp['price']
                        self.account_info['des'] = tmp['title']
                        url1 = "https://www.pzds.com/goodsDetails/" + bianhao + "/6"

                        payload = {}
                        headers1 = {
                            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
                            'Accept-Encoding': 'gzip, deflate, zstd',
                            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                            'Cache-Control': 'no-cache',
                            'Connection': 'keep-alive',
                            'DNT': '1',
                            'Host': 'www.pzds.com',
                            'Pragma': 'no-cache',
                            'Upgrade-Insecure-Requests': '1',
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0',
                        }

                        response1 = requests.request("GET", url1, headers=headers1, data=payload)
                        ans = re.search('已用天赏石([0-9]+)', self.account_info['des'])
                        preguose = re.search('([0-9]+)国色值', self.account_info['des'])
                        guose = -1 if not preguose else int(preguose.group(1))
                        pretianni = re.search('天霓染([0-9]+)', self.account_info['des'])
                        tianni = 0 if not pretianni else int(pretianni.group(1))
                        # print('已用{ans}，国色值{guose}，自染{tianni}'.format(ans=ans,guose=guose,tianni=tianni))
                        todismin = 0
                        if tianni * 8000 > guose:
                            todismin = tianni * 2
                        tianshang = (0 if ans is None else int(ans.group(1))) - todismin
                        self.account_info['danjia'] = self.account_info['price'] / tianshang if tianshang != 0 else 999
                        qufuzuhe = str(tmp['simpleMessage']).split('-')
                        self.account_info['qufu'] = qufuzuhe[len(qufuzuhe) - 1]
                        if account_checker.checkExist(self.account_info['des']) or account_checker.checkExist(
                                response1.text):
                            account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1779601135@qq.com',
                                                       self.account_info['price'] )
                            account_checker.send_email( self.account_info['qufu']+self.account_info['des'], 'w17606748805@163.com',
                                                       self.account_info['price'] )
                            account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1534326708@qq.com',
                                                       self.account_info['price'] )
                            # account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1534326708@qq.com',
                            #                            self.account_info['price'] )
                            # account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '799103682@qq.com',
                            #                            self.account_info['price'] )
                        # if  tianshang >=10 and self.account_info['danjia']<=130:
                        #     account_checker.send_email( self.account_info['qufu']+self.account_info['des'], 'wang330330@qq.com',
                        #                                self.account_info['price'] )
                        # if account_checker.checkExist(self.account_info['des']) or account_checker.checkExist(
                        #         response1.text) or '绝域孤石' in response1.text :
                        #     account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1779601135@qq.com',
                        #                                self.account_info['price'] )
                        #     account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1534326708@qq.com',
                        #                                self.account_info['price'] )
                            # account_checker.send_email( self.account_info['qufu']+self.account_info['des'], '1491012675@qq.com',
                            #                            self.account_info['price'] )
                        self.check_and_notify_users()
                        sql = f"insert into {tablename}(bianhao,price,danjia,des,qufu) values('{bianhao}',{self.account_info['price']},{self.account_info['danjia']},'{self.account_info['des'][:500]}','{self.account_info['qufu']}') "
                        self.cursor.execute(sql)
                        self.db.commit()
                except Exception as eee:
                    self.db.rollback()
                    print('getpanzhidata:' + eee.__str__())
        except  Exception as e:
            self.db.rollback()
            print('getpanzhidata:' + e.__str__())

    def clean_expired_users(self):
        try:
            with self.db.cursor() as cursor:
                sql = f"DELETE FROM {username} WHERE expiration_date < CURDATE()"
                cursor.execute(sql)
                self.db.commit()
        except Exception as e:
            print(f"Error cleaning expired users: {e}")
            self.db.rollback()


if __name__ == '__main__':
    account_checker = AccountChecker()
    while True:
        print(1)
        account_checker.clean_expired_users()
        account_checker.getpanzhidata()
        time.sleep(20)
